﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace PlayNote
{
    /// <summary>
    /// TipWin.xaml 的交互逻辑
    /// </summary>
    public partial class TipWin : Window
    {
        public TipWin()
        {
            InitializeComponent();
            //setCenter();
            Duration duration =(Duration) this.FindResource("span");
            TimeSpan timeSpan = duration.TimeSpan;
            Task.Run(async () => {
                await Task.Delay(timeSpan);
                this.Dispatcher.Invoke(() =>
                {
                    this.Close();
                });
            });
        }

        public static void Show(Window window)
        {
            // 获取当前窗口的句柄
            IntPtr windowHandle = new WindowInteropHelper(window).Handle;

            // 获取当前窗口所在的监视器
            IntPtr hMonitor = MonitorFromWindow(windowHandle, MONITOR_DEFAULTTONEAREST);
            if (hMonitor == IntPtr.Zero)
            {
                MessageBox.Show("无法获取监视器句柄");
                return;
            }

            MONITORINFO monitorInfo = new MONITORINFO();
            monitorInfo.cbSize = Marshal.SizeOf(typeof(MONITORINFO));
            if (!GetMonitorInfo(hMonitor, ref monitorInfo))
            {
                MessageBox.Show($"无法获取监视器信息，错误代码：{Marshal.GetLastWin32Error()}");
                return;
            }

            // 获取当前监视器的工作区信息
            RECT workArea = monitorInfo.rcWork;

            TipWin tipWin = new TipWin();
            tipWin.LayoutUpdated += (s, e) =>
            {
                tipWin.Left = workArea.left + (workArea.right - workArea.left - tipWin.Width) / 2;
                tipWin.Top = workArea.top;
            };
            tipWin.Show();
        }


        [DllImport("user32.dll", SetLastError = true)]
        public static extern IntPtr MonitorFromWindow(IntPtr hwnd, uint dwFlags);

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool GetMonitorInfo(IntPtr hMonitor, ref MONITORINFO lpmi);

        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
        public struct MONITORINFO
        {
            public int cbSize;
            public RECT rcMonitor;
            public RECT rcWork;
            public uint dwFlags;
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct RECT
        {
            public int left;
            public int top;
            public int right;
            public int bottom;
        }

        private const uint MONITOR_DEFAULTTONEAREST = 2;
    }
}
